var map;
var MAP_CONTENT = 'map';
var ABOUT_CONTENT = 'about';
var STRING_EMPTY = '';
var NULL = 'null';

var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;

var PHONE_WIDTH = 730;
var PHONE_HEIGHT = 960;
var MAX_TIME = 300000; //5 minutes

var HOME_POSITION;

//paging 
var offset = 0;
var limit = 20;

var showContent = function(input) {
	if (input != MAP_CONTENT) {
		$("#main").css("display", "block");
		$("#map_canvas").css("display", "none");
	} else {
		$("#main").css("display", "none");
		$("#map_canvas").css("display", "block");
	}
}

var successFn = function(resp) {
	var data = '';
	if (resp) {
		// getting the data from the response object
		data = resp.data;
	}
	return data;
}

var errorFn = function(resp) {
	//TODO
}

//function to get the data by setting url, filter, success function and error function
var getUserPostion = function(url, phone, successFn, errorFn) {
	// making the ajax call
	$.ajax({
		url : url+'?phone='+phone,
		type : "GET",
		data : phone,
		success : function(resp) {
			// calling the user defined success function
			if (successFn)
				successFn(resp);
		},
		error : function(e) {
			// calling the user defined error function
			if (errorFn)
				errorFn(e);
		}
	});
}

//Get avatar path
var getAvatar = function(user) {
	return 'http://graph.facebook.com/'+user.user_id+'/picture';
} 

var getPopupInfo = function(user) {
	var online = isOnline(user.located_time)==true ? 'online':'offline';
	var info = '<div><ul>'+
					'<li><a href=\''+user.link+'\'  target=\'_blank\'>'+user.fullname+'</a></li>'+
					'<li>'+ user.gender + '</li>'+
					'<li>'+user.located_time+'</li>'+
					'<li>'+online+'</li>'+
					'</ul></div>';
	return info;
} 

var isOnline = function(time) {
	var date = convertDateTime(time);
	var current = new Date();
	var d = Date.parse(current) - Date.parse(date);
	if ((Date.parse(current) - Date.parse(date)) < MAX_TIME)
		return true;
	return false;
}

function convertDateTime(time){
	
	var month_abbrs = {
                       'Jan': '01',
                       'Feb': '02',
                       'Mar': '03',
                       'Apr': '04',
                       'May': '05',
                       'Jun': '06',
                       'Jul': '07',
                       'Aug': '08',
                       'Sep': '09',
                       'Oct': '10',
                       'Nov': '11',
                       'Dec': '12'
					};
//	Date('2011-04-11T11:51:00')
//	Mon Mar 24 22:59:40 ICT 2014
    var dateTime = time.split(" ");
    return new Date(dateTime[5]+'-'+month_abbrs[dateTime[1]]+'-'+dateTime[2]+'T'+dateTime[3]);
}

//set Profile
var setProfile = function(user) {
	var avatar = getAvatar(user);
	//set info to avatar
	$('#avatar').attr('src', avatar);
	$('#avatarname').text(user.fullname);
	$('#avataraccount').text(user.username);
	
	//set profile
	if (user.fullname != '' && user.fullname != 'null') {
		$('#fullname').val(user.fullname);
	}
	if (user.gender != '' && user.gender != 'null') {
		$('#gender').val(user.gender);
	}
	
	if (user.link != '' && user.link != 'null') {
		$('#link').val(user.link);
	}
	
	if (user.birthday != '' && user.birthday != 'null') {
		$('#birthday').val(user.birthday);
	}
	
	if (user.interested_in != '' && user.interested_in != 'null') {
		$('#interested_in').val(user.interested_in);
	}
	
	if (user.relationship_status != '' && user.relationship_status != 'null') {
		$('#relationship_status').val(user.relationship_status);
	}
	
	if (user.email != '' && user.email != 'null') {
		$('#email').val(user.email);
	}
	if (user.phone != '' && user.phone != 'null') {
		$('#phone').val(user.phone);
	}
	
	if (user.username != '' && user.username != 'null') {
		$('#username').val(user.username);
	}
	
}

var getIcon = function(avatar) {
	var sizeX = 100;
	var sizeY = 100;
	var scaledSizeX = 50;
	var scaledSizeY = 50;
	if (SCREEN_WIDTH < 750) {
		var sizeX = 50;
		var sizeY = 50;
		var scaledSizeX = 40;
		var scaledSizeY = 40;
	} 
	
	var icon = {
			url : avatar,
			size : new google.maps.Size(sizeX, sizeY),
			origin : new google.maps.Point(0, 0),
			anchor : new google.maps.Point(17, 34),
			scaledSize : new google.maps.Size(scaledSizeX, scaledSizeY)
		};
	
	return icon;
}

//load map with users
var loadMap = function(users) {
	
	//Get user login to initialize map
	var user = users[0];
	var markers = Array();
	var infoWindows = Array();
	
	//Set profile
	setProfile(user);
	
//	var shape = {
//		      coord: [1, 1, 100],
//		      type: 'circle'
//		  };
	
	//set map options
	var mapOptions
	if (user.located == NULL) {
		mapOptions = {
				zoom : 8,
				center : new google.maps.LatLng(40.111689,-78.134766),//new york
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
		HOME_POSITION = new google.maps.LatLng(40.111689,-78.134766);
	} else {
		mapOptions = {
				zoom : 8,
				center : new google.maps.LatLng(user.latitude, user.longitude),
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
		HOME_POSITION = new google.maps.LatLng(user.latitude, user.longitude);
		
		
	}
	
	//load map with user's position
	map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
	
	// Set the last users
	for ( var i = 0; i < users.length; i++) {
		
		var user = users[i];
		var avatar = getAvatar(user);
		var image = getIcon(avatar);
		
		if (i == 0) {
			var marker = new google.maps.Marker({
			     position: new google.maps.LatLng(user.latitude, user.longitude),
			     map: map,
			     icon: image,
			     title: user.username,
			     draggable: true,
//			     shape: shape,
			     animation: google.maps.Animation.BOUNCE,
			     infoWindowIndex : i
			 });
		} else {
			var marker = new google.maps.Marker({
			     position: new google.maps.LatLng(user.latitude, user.longitude),
			     map: map,
			     icon: image,
			     title: user.username,
			     draggable: true,
//			     shape: shape,
//			     animation: google.maps.Animation.BOUNCE,
			     infoWindowIndex : i
			 });
		}
			
		
	    var label = new Label({
	        map: map,
	        title: user.fullname
	      });
	    label.bindTo('position', marker, 'position');
	    label.bindTo('text', marker, 'position');
	    
	    var info = getPopupInfo(user);
	    infoWindow = new google.maps.InfoWindow({
			content : info
		});
		//google.maps.event.addListener(marker[i], "click", function (e) { iw[i].open(map, marker[i]); });
		google.maps.event.addListener(marker, "click",function(e) {
							infoWindows[this.infoWindowIndex].open(map, this);
						});
		infoWindows.push(infoWindow);
		markers.push(marker);
	}
}

var loadMapMore = function(users) {
	var markers = Array();
	var infoWindows = Array();
	// Set the last users
	for ( var i = 0; i < users.length; i++) {
		
		var user = users[i];
		var avatar = getAvatar(user);
		var image = getIcon(avatar);
		
		if (i == 0) {
			var marker = new google.maps.Marker({
			     position: new google.maps.LatLng(user.latitude, user.longitude),
			     map: map,
			     icon: image,
			     title: user.username,
			     draggable: true,
			     animation: google.maps.Animation.BOUNCE,
			     infoWindowIndex : i
			 });
		} else {
			var marker = new google.maps.Marker({
			     position: new google.maps.LatLng(user.latitude, user.longitude),
			     map: map,
			     icon: image,
			     title: user.username,
			     draggable: true,
			     infoWindowIndex : i
			 });
		}
			
		
	    var label = new Label({
	        map: map,
	        title: user.fullname
	      });
	    label.bindTo('position', marker, 'position');
	    label.bindTo('text', marker, 'position');
	    
	    var info = getPopupInfo(user);
	    infoWindow = new google.maps.InfoWindow({
			content : info
		});
		//google.maps.event.addListener(marker[i], "click", function (e) { iw[i].open(map, marker[i]); });
		google.maps.event.addListener(marker, "click",function(e) {
							infoWindows[this.infoWindowIndex].open(map, this);
						});
		infoWindows.push(infoWindow);
		markers.push(marker);
	}
}

var loadMoreFriends = function() {
	//load user account from cookie
	var useraccount = $.cookie('useraccount');
	if (useraccount != '' && useraccount != null) {
		offset = offset + 20;
		FB.api('/me/friends?offset='+offset+'&limit='+limit, function(response) {
		      
			$.ajax({
				url : "/index?action=getpositionusers&id="+useraccount,
				type: 'POST',
		        dataType: 'json',
		        data: JSON.stringify(response),
		        contentType: 'application/json',
		        mimeType: 'application/json',
				success : function(resp) {
					if (resp != null) {
						// getting the data from the response object
						var data = resp.data;
						
						//initialize map
						if(data.length > 0)
							loadMapMore(data)
					}
				}
				
			});
			
		});
	} else {//not login
		//Go to index page
		document.location.href = '/index.html';
	}
}

var initMap = function() {
	
	//load user account from cookie
	var useraccount = $.cookie('useraccount');
	if (useraccount != '' && useraccount != null) {
		FB.api('/me/friends?offset=15&limit=20', function(response) {
		      
			$.ajax({
				url : "/index?action=getpositionusers&id="+useraccount,
				type: 'POST',
		        dataType: 'json',
		        data: JSON.stringify(response),
		        contentType: 'application/json',
		        mimeType: 'application/json',
				success : function(resp) {
					if (resp != null) {
						// getting the data from the response object
						var data = resp.data;
						
						//initialize map
						if(data.length > 0)
							loadMap(data);
					}
				}
				
			});
			
//			$.ajax({
//				url : "/index?action=searchusers&id="+useraccount+"&latitude=10.800933&longitude=107.20459",
//				type: 'POST',
//		        dataType: 'json',
//		        data: JSON.stringify(response),
//		        contentType: 'application/json',
//		        mimeType: 'application/json',
//				success : function(resp) {
//					if (resp != null) {
//						// getting the data from the response object
//						var data = resp.data;
//						
//						//initialize map
//						if(data.length > 0)
//							loadMap(data);
//					}
//				}
//				
//			});
				
		
		    });
	} else {//not login
		//Go to index page
		document.location.href = '/index.html';
	}
}

var moveMapToFirtMaker = function() {
	map.panTo(HOME_POSITION);
}


var searchUser = function() {
	
}
